﻿


using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.Workflow;

using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;

using System.Text;


using System.Web;
using System.Web.UI.WebControls;

using System.Data;

using System.Globalization;

using System.Diagnostics;
using System.Diagnostics.Eventing;


namespace ProtocolsFeature.Layouts.ProtocolsFeature
{
    public partial class SendProtocol : LayoutsPageBase
    {

        public bool IsComplete = false;
        public bool IsStarted = false;
        public bool DocumentLoaded = false;
        public string ProtocolID = "";


        EventLog LogToSystem = new EventLog();


        protected void Page_Load(object sender, EventArgs e)
        {


            peopleForward.IsValid = true;


            if (!IsPostBack)
            {

                InitializeDocumentStatus();



                BindApprovers();


                LocalizeForm();

            }



        }


        protected void  InitializeDocumentStatus()
        {

            string protocolID="";
        

            if (Request.QueryString["List"] != null && Request.QueryString["Item"] != null )
            {


                SPListItem item = SPContext.Current.Web.Lists[new Guid(Request.QueryString["List"])].GetItemById(int.Parse(Request.QueryString["Item"]));


                // Does this document already have a protocol id?
                if (item[item.ParentList.Fields.GetFieldByInternalName("ProtocolID").Id] != null)
                {
                    protocolID = (string)item[item.ParentList.Fields.GetFieldByInternalName("ProtocolID").Id];

                    this.IsComplete = true;
                }


                if (!string.IsNullOrEmpty(protocolID))
                {
                    this.ProtocolID = protocolID;
                }
                else
                {
                    if (item.Workflows.Count > 0 && item.Workflows[0].IsCompleted == false)
                    {
                        this.IsStarted = true;
                    }


                }
                    

            }

             
        
        }

     

        protected void LocalizeForm()
        {



            btnAdd.Text = Resource1.SendForProtocolForm_AddApprover;
            btnSave.Text = Resource1.SendForProtocolForm_Save;
            btnStart.Text = Resource1.SendForProtocolForm_StartWorkflow;


            btnSave.Visible = false;
            btnStart.Visible = false;

            btnCancel.Text = Resource1.SendForProtocolForm_Close;


            panelAssign.Visible = false;


            labelApprovers.Text = Resource1.SendForProtocolForm_AddApprovalUser;

            labelApproversList.Text = Resource1.SendForProtocolForm_ApprovalUsers;


            labelMessage.Text = Resource1.SendForProtocolForm_StartDetails;

            if (this.IsComplete)
            {
                labelMessage.Text = string.Format(Resource1.SendForProtocolForm_ProtocolComplete,this.ProtocolID);



            }
            else
            {

                if (this.IsStarted)
                {

                    btnSave.Visible = false;
                    btnStart.Visible = false;

                    panelAssign.Visible = false;

                    labelMessage.Text = Resource1.SendForProtocolForm_ProtocolInProgress;

                }
                else
                {
                    panelAssign.Visible = true;



                    btnSave.Visible = true;
                    btnStart.Visible = true;

                }


            }


        }



        #region Approver methods


        

  

        protected string GetUserDisplayNames(string UserList)
        {


            string DisplayNameList = "";

            if ((UserList != null) && (UserList.Length > 0))
            {

                // Ensure we have the correct delimiter
                UserList = UserList.Replace(',', ';');

                SPSite site = null;
                SPWeb web = null;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    site = new SPSite(Microsoft.SharePoint.SPContext.Current.Web.Url);
                    web = site.OpenWeb();

                    string[] usersArray = UserList.Split(';');

                    for (int i = 0; i < usersArray.Length; i++)
                    {
                        string username = usersArray[i].ToString();

                        if (username.Length > 0)
                        {
                            try
                            {
                                SPUser User = web.SiteUsers[username];



                                if (DisplayNameList.Length > 0)
                                    DisplayNameList = string.Concat(DisplayNameList, ";", User.Name);
                                else
                                    DisplayNameList = User.Name;

                            }
                            catch
                            {
                                // If we cant get the Display Name - then just show what we have
                                if (DisplayNameList.Length > 0)
                                    DisplayNameList = string.Concat(DisplayNameList, ";", username);
                                else
                                    DisplayNameList = username;

                            }

                        }

                    }

                    web.Dispose();
                    site.Dispose();




                });


            }


            return DisplayNameList;

        }




        protected void btnAddApprover_Click(object sender, EventArgs e)
        {


            if (!string.IsNullOrEmpty(peopleForward.CommaSeparatedAccounts))
            {



                if (peopleForward.CommaSeparatedAccounts.Length > 0)
                {
                    AddApprover(peopleForward.CommaSeparatedAccounts);

                    BindApprovers();

                }

                peopleForward.CommaSeparatedAccounts = "";

            }

        }



        public void gridApprovers_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            string recNo = gridApprovers.Rows[e.RowIndex].Cells[1].Text;

            DataTable dtApprovers = null;

            if (ViewState["Approvers"] != null)
            {
                dtApprovers = (DataTable)ViewState["Approvers"];
            }


            if (dtApprovers != null && dtApprovers.Rows.Count > 0)
            {

                int recToDelete = 0;
                bool found = false;

                foreach (DataRow row in dtApprovers.Rows)
                {

                    if (row["RecNo"].ToString() == recNo)
                    {
                        found = true;
                        break;
                    }
                    recToDelete++;
                }

                if (found)
                {
                    dtApprovers.Rows[recToDelete].Delete();
                    dtApprovers.AcceptChanges();

                    ViewState["Approvers"] = dtApprovers;
                }

            }

          
            BindApprovers();
        }



        protected void SaveApproversToDocument()
        {

            SPListItem item = SPContext.Current.Web.Lists[new Guid(Request.QueryString["List"])].GetItemById(int.Parse(Request.QueryString["Item"]));


            item[item.ParentList.Fields.GetFieldByInternalName("ProtocolApprovers").Id] = GetApproversSPFieldUserValueCollection();
            item.SystemUpdate();

        }

        protected void AddApprover(string account)
        {


            DataTable dtApprovers = null;


            if (ViewState["Approvers"] != null)
            {
                dtApprovers = (DataTable)ViewState["Approvers"];
            }
            else
            {
                dtApprovers = new DataTable();
                dtApprovers.Columns.Add(new System.Data.DataColumn("ID", System.Type.GetType("System.String")));
                dtApprovers.Columns.Add(new System.Data.DataColumn("RecNo", System.Type.GetType("System.String")));
                dtApprovers.Columns.Add(new System.Data.DataColumn("Name", System.Type.GetType("System.String")));
                dtApprovers.Columns.Add(new System.Data.DataColumn("Login", System.Type.GetType("System.String")));


                ViewState.Add("Approvers", dtApprovers);
            }


            SPFieldUserValue newUser = GetUserListForPeopleField(account);


            if (newUser != null)
            {
                DataRow row;
                row = dtApprovers.NewRow();
                row["ID"] = newUser.User.ID;
                row["Name"] = newUser.User.Name;
                row["Login"] = newUser.User.LoginName;

                dtApprovers.Rows.Add(row);
                dtApprovers.AcceptChanges();

                ViewState["Approvers"] = dtApprovers;
            }

        }


        protected void BindApprovers()
        {

           
            DataTable dtApprovers = null;

            if (!this.IsComplete)
            {

                if (ViewState["Approvers"] != null)
                {
                    dtApprovers = (DataTable)ViewState["Approvers"];
                }
                else
                {

                    dtApprovers = new DataTable();
                    dtApprovers.Columns.Add(new System.Data.DataColumn("ID", System.Type.GetType("System.String")));
                    dtApprovers.Columns.Add(new System.Data.DataColumn("RecNo", System.Type.GetType("System.String")));
                    dtApprovers.Columns.Add(new System.Data.DataColumn("Name", System.Type.GetType("System.String")));
                    dtApprovers.Columns.Add(new System.Data.DataColumn("Login", System.Type.GetType("System.String")));

                    ViewState.Add("Approvers", dtApprovers);

                    #region Load the details from the document record

                    InitializeApproversTable(ref dtApprovers);

                    // If no approvers - insert a blank row
                    //if (dtApprovers.Rows.Count <= 0)
                    //{

                    //    DataRow row;
                    //    row = dtApprovers.NewRow();
                    //    row["ID"] = "";
                    //    row["Name"] = "";
                    //    row["Login"] = "";

                    //    dtApprovers.Rows.Add(row);
                    //    dtApprovers.AcceptChanges();
                    //}


                    #endregion


                }





                int recNo = 1;
                foreach (DataRow row in dtApprovers.Rows)
                {
                    row["RecNo"] = recNo.ToString();
                    row.AcceptChanges();
                    recNo++;

                }
                dtApprovers.AcceptChanges();


                ViewState["Approvers"] = dtApprovers;


                gridApprovers.DataSource = dtApprovers;
                gridApprovers.DataBind();

            }

            if  (dtApprovers!=null && dtApprovers.Rows.Count > 0)
                labelApproversList.Visible = true;
            else
                labelApproversList.Visible = false;
                

        }


        private SPFieldUserValue GetSPFieldUserValue(SPListItem item, SPField field)
        {

            string currentValue = item[field.Title].ToString();
            SPFieldUser userField = (SPFieldUser)field;
            SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(currentValue);

            return fieldValue;

        }
        private SPUser GetSPUser(SPListItem item, SPField field)
        {

            string currentValue = item[field.Title].ToString();
            SPFieldUser userField = (SPFieldUser)field;
            SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(currentValue);

            return fieldValue.User;

        }

        private SPFieldUserValue GetUserListForPeopleField(string userNamesList)
        {

            SPFieldUserValue userValue = null;

            if (!string.IsNullOrEmpty(userNamesList))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite site = new SPSite(Microsoft.SharePoint.SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {

                            site.AllowUnsafeUpdates = true;
                            web.AllowUnsafeUpdates = true;

                            string[] split = userNamesList.Split(new Char[] { ',', ';' });

                            foreach (string userName in split)
                            {
                                try
                                {
                                    SPUser user = web.EnsureUser(userName);

                                    userValue = new SPFieldUserValue(web, user.ID, user.Name);

                                    break;
                                }
                                catch (Exception codeException)
                                {
                                    WriteError(codeException);
                                }

                            }

                        }

                    }


                });


            }
            return userValue;

        }

        private SPFieldUserValueCollection GetUserListForMultiPeopleField(string userNamesList)
        {

            SPFieldUserValueCollection userValueList = new SPFieldUserValueCollection();


            if (!string.IsNullOrEmpty(userNamesList))
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite site = new SPSite(Microsoft.SharePoint.SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {

                            site.AllowUnsafeUpdates = true;
                            web.AllowUnsafeUpdates = true;

                            string[] split = userNamesList.Split(new Char[] { ',', ';' });

                            foreach (string userName in split)
                            {
                                try
                                {
                                    SPUser user = web.EnsureUser(userName);

                                    SPFieldUserValue userValue = new SPFieldUserValue(web, user.ID, user.Name);

                                    if (userValue != null)
                                    {
                                        userValueList.Add(userValue);
                                    }

                                }
                                catch (Exception codeException)
                                {
                                    WriteError(codeException);
                                }

                            }

                        }
                    }
                });


            }
            return userValueList;

        }





        protected void InitializeApproversTable(ref DataTable table)
        {


            try
            {


                SPListItem item = SPContext.Current.Web.Lists[new Guid(Request.QueryString["List"])].GetItemById(int.Parse(Request.QueryString["Item"]));

                SPFieldUserValueCollection approvers = (SPFieldUserValueCollection)item[item.ParentList.Fields.GetFieldByInternalName("ProtocolApprovers").Id];


                if (approvers != null && approvers.Count > 0)
                {

                    foreach (SPFieldUserValue approver in approvers)
                    {
                        DataRow row;
                        row = table.NewRow();
                        row["ID"] = approver.User.ID;
                        row["Name"] = approver.User.Name;
                        row["Login"] = approver.User.LoginName;

                        table.Rows.Add(row);
                    }

                    table.AcceptChanges();

                }

            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }


        }



        protected SPFieldUserValueCollection GetApproversSPFieldUserValueCollection()
        {


            SPFieldUserValueCollection approvers = null;
            DataTable dtApprovers = null;

            try
            {


                if (ViewState["Approvers"] != null)
                    dtApprovers = (DataTable)ViewState["Approvers"];


                if (dtApprovers != null && dtApprovers.Rows.Count > 0)
                {
                    approvers = new SPFieldUserValueCollection();

                    foreach (DataRow  row in dtApprovers.Rows)
                    {
                        try
                        {
                            SPUser user = SPContext.Current.Web.EnsureUser( row["Login"].ToString() );

                            SPFieldUserValue userValue = new SPFieldUserValue(SPContext.Current.Web, user.ID, user.Name);

                            approvers.Add( userValue );

                        }
                        catch (Exception codeException)
                        {
                            WriteError(codeException);
                        }


                        
                    }
                }

            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }


            return approvers;

        }


        
        #endregion




  
        #region Button actions




        public void btnSave_Click(object sender, EventArgs e)
        {
            SaveApproversToDocument();

            CloseForm();
        }

        public void btnStart_Click(object sender, EventArgs e)
        {


            DataTable dtApprovers = (DataTable)ViewState["Approvers"];

            if (dtApprovers != null && dtApprovers.Rows.Count > 0)
            {


                SaveApproversToDocument();

                StartWorkflow();

                CloseForm();

            }
        }


        public void btnCancel_Click(object sender, EventArgs e)
        {
            CloseForm();
        }


        private void CloseForm()
        {
            if ((SPContext.Current != null) && SPContext.Current.IsPopUI)
            {
                this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                this.Context.Response.Flush();
                this.Context.Response.End();
            }
            else
            {
                string str = this.Page.Request.QueryString["Source"];
                if ((str != null) && (str.Length > 0))
                {
                    SPUtility.Redirect(string.Empty, SPRedirectFlags.UseSource, this.Context);
                }
            }
        }



        #endregion



        private void WriteError(Exception ex)
        {
            LogToSystem.Source = "SharePoint 2010 Protocols Library";
            LogToSystem.WriteEntry(ex.Message + " : " + ex.StackTrace, EventLogEntryType.Error);

        }
    

        #region workflow methods

        protected void StartWorkflow()
        {

            SPWeb web = SPContext.Current.Web;
 
            int id = int.Parse(  Request.QueryString["Item"] );

            SPList list =  web.GetList(string.Format("{0}/Lists/{1}", web.ServerRelativeUrl, "OutgoingDocuments"));



            SPWorkflowManager manager = SPContext.Current.Site.WorkflowManager;
            
            SPWorkflowAssociation association = list.WorkflowAssociations[0];

            SPListItem item = list.GetItemById(id);
       


            item[item.ParentList.Fields.GetFieldByInternalName("SentForProtocolBy").Id] =new SPFieldUserValue(SPContext.Current.Web,SPContext.Current.Web.CurrentUser.ID,  SPContext.Current.Web.CurrentUser.Name );
            item.SystemUpdate();


            //get workflow association data
            string data = association.AssociationData;


            SPWorkflow wf = manager.StartWorkflow(item, association,data,true);

        }


        #endregion


     


    }
}
